package cn.tedu.weibo1.controller;

import cn.tedu.weibo1.mapper.UserMapper;
import cn.tedu.weibo1.pojo.dto.UserDTO;
import cn.tedu.weibo1.pojo.dto.UserLoginDTO;
import cn.tedu.weibo1.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired(required = false)
    UserMapper userMapper;

    @RequestMapping("currentUser")
    public UserVO currentUser(HttpSession session) {
        return (UserVO) session.getAttribute("user");
    }

    @RequestMapping("logout")
    public void logout(HttpSession session) {
        session.removeAttribute("user");
    }

    @RequestMapping("login")
    public int login(@RequestBody UserLoginDTO user, HttpSession session) {
        System.out.println("user = " + user);
        UserVO u = userMapper.selectByUsername(user.getUsername());
        if (u != null) {
            if (u.getPassword().equals(user.getPassword())) {
                session.setAttribute("user", u);
                return 1;
            }
            return 3;
        }
        return 2;
    }

    @RequestMapping("reg")
    public int reg(@RequestBody UserDTO user) {
        System.out.println("user = " + user);
        UserVO u = userMapper.selectByUsername(user.getUsername());
        if (u != null) {
            return 2;//用户名已存在
        }
        userMapper.reg(user);
        return 1;
    }
}
